

package com.hazelcast.client.impl.protocol.codec.builtin;

import com.hazelcast.client.impl.protocol.ClientMessage;

import java.math.BigDecimal;
import java.math.BigInteger;

import static com.hazelcast.client.impl.protocol.ClientMessage.NULL_FRAME;
import static com.hazelcast.client.impl.protocol.codec.builtin.CodecUtil.nextFrameIsNullEndFrame;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;

public final class BigDecimalCodec {

    private BigDecimalCodec() {
    }

    public static void encode(ClientMessage clientMessage, BigDecimal value) {
        byte[] body = value.unscaledValue().toByteArray();

        byte[] buffer = new byte[INT_SIZE_IN_BYTES + body.length + INT_SIZE_IN_BYTES];
        encodeInt(buffer, 0, body.length);
        System.arraycopy(body, 0, buffer, INT_SIZE_IN_BYTES, body.length);
        encodeInt(buffer, INT_SIZE_IN_BYTES + body.length, value.scale());

        clientMessage.add(new ClientMessage.Frame(buffer));
    }

    public static void encodeNullable(ClientMessage clientMessage, BigDecimal value) {
        if (value == null) {
            clientMessage.add(NULL_FRAME.copy());
        } else {
            encode(clientMessage, value);
        }
    }

    public static BigDecimal decode(ClientMessage.ForwardFrameIterator iterator) {
        byte[] buffer = iterator.next().content;

        int contentSize = decodeInt(buffer, 0);
        byte[] body = new byte[contentSize];
        System.arraycopy(buffer, INT_SIZE_IN_BYTES, body, 0, contentSize);
        int scale = decodeInt(buffer, INT_SIZE_IN_BYTES + contentSize);

        return new BigDecimal(new BigInteger(body), scale);
    }

    public static BigDecimal decodeNullable(ClientMessage.ForwardFrameIterator iterator) {
        return nextFrameIsNullEndFrame(iterator) ? null : decode(iterator);
    }
}
